package com.example.demo.controller;

import com.example.demo.commom.AjaxResult;
import com.example.demo.commom.UserSessionUtils;
import com.example.demo.entity.Articleinfo;
import com.example.demo.entity.UpVoteinfo;
import com.example.demo.entity.Userinfo;
import com.example.demo.service.UpvoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-04-10
 * Time:20:29
 */
@RestController
@RequestMapping("/vote")
public class UpvoteController {
    @Autowired
    private UpvoteService upvoteService;
    //文章点赞
    @RequestMapping("/upvote")
    public AjaxResult upvote(Integer artid, HttpServletRequest request) {
        //1、判空
        if(artid == null || artid < 1) {
            return AjaxResult.fail("参数有误",-1);
        }
        //2、用户是否登录
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null) {
            return AjaxResult.fail("请登录后点赞",-1);
        }
        if(userinfo.getId() < 1) {
            return AjaxResult.fail("参数有误",-1);
        }
        //3、点赞
        //判断是否已经点赞了
        UpVoteinfo upVoteinfo = upvoteService.haveVote(artid,userinfo.getId());
        //未点赞
        if(upVoteinfo == null) {
            //进行点赞
            UpVoteinfo vote = new UpVoteinfo();
            vote.setArtid(artid);
            vote.setUserid(userinfo.getId());
            upvoteService.upvote(vote);
            return AjaxResult.success("点赞成功");
        }
        //以前点过赞
        if(upVoteinfo.getState() == 0) {
            upVoteinfo.setState(1);
            //将未点赞修改为已点赞
            upvoteService.upvoteState(upVoteinfo.getId(),upVoteinfo.getState());
            return AjaxResult.success("点赞成功");
        }
        //已经点赞了，此时点击表示取消点赞
        if(upVoteinfo.getState() == 1) {
            upVoteinfo.setState(0);
            //将未点赞修改为已点赞
            upvoteService.upvoteState(upVoteinfo.getId(),upVoteinfo.getState());
            return AjaxResult.success("取消点赞");
        }
        return AjaxResult.success("执行有误",-1);
    }
    @RequestMapping("/votecount")
    public AjaxResult voteCount(Integer artid) {
        //1、判空
        if(artid == null || artid < 1) {
            return AjaxResult.fail("参数有误",-1);
        }
        //2、查找点赞数
        return AjaxResult.success(upvoteService.voteCount(artid));
    }
}
